package jadeCW.behaviour;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jadeCW.HospitalAgent;
import jadeCW.output.Printer;

/**
 * Respond To Proposal 2 behaviour class
 * 
 * @author br08, dac108, dv08
 */
public class RespondToProposal2 extends CyclicBehaviour {
	/**
	 * Generated serialisation ID
	 */
	private static final long serialVersionUID = -449916307829308375L;

	@Override
	public void action() {
		// must be run on a hospital
		if (!(myAgent instanceof HospitalAgent)) {
			return;
		}

		HospitalAgent hospital = (HospitalAgent) myAgent;

		// create template to receive proposals
		MessageTemplate template = MessageTemplate.and(MessageTemplate
				.MatchPerformative(ACLMessage.REQUEST), MessageTemplate
				.MatchConversationId(ProposeSwap.TYPE));

		// receive messages
		ACLMessage message = hospital.receive(template);

		// if not proposal received, block and try again
		if (message == null) {
			block();
			return;
		}
		
		// get the desired appointment from the message content
		int desiredAppointment = Integer.parseInt(message.getContent());
		
		Printer.printRTP2Receive(hospital, desiredAppointment, message.getSender());

		// create reply
		ACLMessage reply = message.createReply();

		// get the current owner
		AID owner = hospital.getOwner(desiredAppointment);

		// if the hospital currently owns it
		if (owner == hospital.getAID()) {
			// set up accept message
			reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
			
			Printer.printRTP2SendAccept(hospital, desiredAppointment, message.getSender());
			
			// update the hospital, removing the sender from their current
			// appointment and setting them to the new appointment
			int ownedAppointment = hospital.getAppointment(message.getSender());
			hospital.setAppointment(ownedAppointment, null);
			hospital.setAppointment(desiredAppointment, message.getSender());

		} else {
			// reject as unavailable
			reply.setPerformative(ACLMessage.REJECT_PROPOSAL);
			
			Printer.printRTP2SendReject(hospital, desiredAppointment, message.getSender());
		}

		// send reply
		hospital.send(reply);
	}
}
